/**
 * Created by aurogon-mac on 15/4/25.
 */
var exec = require("child_process").exec;
var querystring = require("querystring"),
    fs = require("fs"),
    formidable = require("formidable");

function index(response, postData, request) {
    console.log("Request handler 'index' was called.");

    //function sleep(milliSeconds) {
    //    var startTime = new Date().getTime();
    //    while (new Date().getTime() < startTime + milliSeconds);
    //}

    //sleep(10000);

    //exec("find /", {timeout: 10000, maxBuffer: 20000*1024},
    //    function(error, stdout, stderr){
    //    response.writeHead(200, {"Content-Type": "text/plain"});
    //    response.write(stdout);
    //    response.end();
    //});

    var body ='<html>' +
        '<head>' +
        '<meta http-equiv="Content-Type" ' +
        'content="text/html; charset=UTF-8" />' +
        '</head>' +
        '<body>' +
        '<form action="/upload" method="post" enctype="multipart/form-data"> ' +
        '<textarea name="text" rows="1" cols="30"></textarea><br/>' +
        '<input type="file" name="upload" /></br>' +
        '<input type="submit" value="Submit" />' +
        '</form>' +
        '</body>' +
        '</html>';
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}

function upload(response, postData, request) {
    console.log("Request handler 'upload' was called.");

    var form = new formidable.IncomingForm();
    console.log("About to parse");
    form.parse(request, function(error, fields, files){
        console.log("Parsing done");
        fs.renameSync(files.upload.path, "/tmp/test.png");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("received image: <br/>");
        response.write("<img src='/show'/>");
        response.write("<a href='/show'>Show</a>");
        response.end();
    });

    //response.writeHead(200, {"Content-Type": "text/plain"});
    //response.write("You've sent the text: " + querystring.parse(postData).text);
    //response.end();
}

function show(response, postData, request) {
    console.log("Request handler 'show' was called.");
    fs.readFile("/tmp/test.png", "binary", function(error, file){
        if (error) {
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(error + "\n");
            response.end();
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");
            response.end();
        }
    })
}

exports.index = index;
exports.upload = upload;
exports.show = show;